package com.qfedu.openplateform.gateway.filter;

import com.qfedu.openplateform.common.entity.LoggerBean;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

public class LogFilter implements HandlerInterceptor {
    ThreadLocal<Date> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //可以记录请求请求开始时间  ---
        // 改时间必须存储到 ThreadLocal 中，因为每一个请求都是一个线程，保存到ThreadLocal 就是为每一个线程存储一个副本
        threadLocal.set(new Date());

        // 不拦截
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoggerBean loggerBean = new LoggerBean();
        Date responseDate = new Date();
        loggerBean.setResponseTime(responseDate); // 响应时间


        // 记录用户的 app_key
        loggerBean.setApp_key(request.getParameter("app_key"));
        // 记录请求的 名字
        loggerBean.setApiName(request.getParameter("method"));

        // 记录请求 的ip
        loggerBean.setRemoteIp(request.getRemoteAddr());

        // 记录整个请求 耗费的时间
        Date startTine = threadLocal.get();
        loggerBean.setReveivceTime(startTine); // 开始响应时间
        loggerBean.setTotalTime(responseDate.getTime() - startTine.getTime());// 响应时长


        try {
            // 记录请求的ip 真正客户端ip
            loggerBean.setServerIp(InetAddress.getLocalHost().getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        loggerBean.setContent(request.getQueryString());

        System.out.println(loggerBean);

    }
}
